<?php
class WbWebSite extends DomSite {
	
	protected $site;

	protected $page;
	
	protected $selectedPages = array();
	
	public function init() {
		if( $_SESSION['wbSiteId'] == null ) {
			$this->site = WbSite::query()->where('t.site <=> NULL AND t.isMainSite=1')->limit(1)->commit();
		} else {
			$this->site = WbSite::load( $_SESSION['wbSiteId'] );
		}
	}

	public function isSelected( $id ) {
		return (bool)$this->selectedPages[$id];
	}
	
	public function analyzeUrl() {
		$args = explode('/', $_GET['args'] );
		$key = array_shift($args);
		
		if( $key != '') {
			if( is_numeric( $key ) ) {
				$this->page = DomAr::load( $key, 'WbPage');
			} else {
				$this->page = WbPage::query()->where('t.urlKey="'.addslashes($key).'"')->limit(1)->commit();
			}
		} else {
			$this->page = WbPage::query()->where('t.site='.(int)$this->site->id.' AND t.isFrontPage=1')->limit(1)->commit();
		}

		if( $this->page ) {
			
			$p = $this->page;
			while( $p ) {
				$this->selectedPages[$p->id] = true;
				$p = $p->parent;
			}
			
			if( $this->page instanceof WbPageLink ) {
				if( strpos($this->page->link, 'http:') !== false or strpos($this->page->link, 'https:') !== false ) {
					header('location: '.$this->page->link);
				} else {
					$_GET['args'] = $this->page->link.'/'.implode('/',$args);
				}
			} else {
				$_GET['args'] = 'Wb/'.lcfirst(get_class($this->page)).'/'.$this->page->id.'/'.implode('/',$args);
			}
		}
		parent::analyzeUrl();
	}
	
	public function __destruct() {
		$_SESSION['wbSiteId'] = $this->site->id;
	}

}